package com.manopservice.controller;

import java.util.HashMap;
import java.util.Map;

import com.manopservice.model.CarBrand;
import com.manopservice.service.CarBrandService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/carBrands")
public class CarBrandController {

	@Autowired
	private CarBrandService carBrandService;

	@RequestMapping(value = "/ShowCarBrands", method = RequestMethod.POST)
	public ModelAndView showCarPart() {
		
		return listCarBrands();
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView saveCarBrand(@ModelAttribute("carBrand") CarBrand  carBrand,
			BindingResult result) {
		carBrandService.saveCarBrand(carBrand);
		return new ModelAndView("redirect:/carBrands.html");
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public ModelAndView deleteCarBrand(@ModelAttribute("carBrand") CarBrand  carBrand,
			BindingResult result) {
		carBrandService.deleteCarBrand(carBrand.getId());
		return new ModelAndView("redirect:/carBrands.html");
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView listCarBrands() {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("carBrands",  carBrandService.listCarBrands());

		return new ModelAndView("carBrandsList", model);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView addCarBrand(@ModelAttribute("carBrand") CarBrand carBrand,
			BindingResult result) {
		return new ModelAndView("addCarBrand");
	}
	
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public ModelAndView editCarBrand(@ModelAttribute("carBrand") CarBrand carBrand,
			BindingResult result) {
		
		CarBrand cb = carBrandService.findCarBrandById(carBrand.getId());
		carBrand.setNameThai(cb.getNameThai());
		carBrand.setNameEng(cb.getNameEng());
				
		return new ModelAndView("editCarBrand");
	}
}